package com.wml.sellPhone.service.impl;

import com.wml.sellPhone.dao.UserMapper;
import com.wml.sellPhone.pojo.User;
import com.wml.sellPhone.service.IEmailService;
import com.wml.sellPhone.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;

/**
 * @author Cheryl
 * @date 2018-06-29 21:32
 */

@Service
public class EmailServiceImpl implements IEmailService {

    @Resource
    private JavaMailSender javaMailSender;
    @Autowired
    private UserMapper userMapper;


    /**
     * 发送邮件
     *
     * @param content
     * @param title
     * @param toName
     */
    @Override
    public void sendEmail(String content, String title, String toName) {
        // 建立邮件消息
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        try {
            messageHelper = new MimeMessageHelper(message, true, "UTF-8");
            // 设置发件人邮箱
            messageHelper.setFrom("1714632267@qq.com");
            // 设置收件人邮箱
            messageHelper.setTo(toName);
            // 邮件主题
            messageHelper.setSubject(title);
            // 邮件内容
            messageHelper.setText(content);
            javaMailSender.send(message);
            System.out.println("发送邮件成功");
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }

    /**
     * 根据用户填写的email地址判断email地址是否存在
     * @param email
     * @return
     */
    @Override
    public boolean judgeEmail(String email, HttpServletRequest request) {
        User user = userMapper.selectByEmail(email);
        if (user == null){
            return false;
        }
        // 将用户保存到session中
        request.getSession().setAttribute(Constant.RESETUSER, user);
        return true;
    }
}
